package com.calvin.study.multithread.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Thread06 {
	
	public static final int MAX_TURN = 5;
	public static final int COMPUTE_TIMES = 100000000;

	public static String getCurThreadName() {
		return Thread.currentThread().getName();
	}

	//1.创建一个Callable接口的实现类，并实现其call()方法。
	static class ReturnableTask implements Callable<Long> {
		
		public Long call() throws Exception {
			System.out.println(getCurThreadName() + " 线程运行开始.");
			long startTime = System.currentTimeMillis();
			Thread.sleep(2000);
			for (int i = 0; i < COMPUTE_TIMES; i++) {
				int j = i * 10000;
			}
			long used = System.currentTimeMillis() - startTime;
			System.out.println(getCurThreadName() + " 线程运行结束. 运行时间：" + used );
			return used;
		}
	}

	public static void main(String[] args) throws InterruptedException {
		ReturnableTask task = new ReturnableTask();
		//2.使用Callable实现类的实例，构造一个FutureTask实例。
		FutureTask<Long> futureTask = new FutureTask<Long>(task);
		//3.使用FutureTask实例作为Thread构造器的target入参， 构造新的Thread线程实例。
		Thread thread = new Thread(futureTask, "[returnableThread]");
		//4.调用start方法启动新线程
		thread.start();//执行 ReturnableTask
		//Thread.sleep(1000);
		//与上面的线程并行执行，这里开始执行main主线程
		System.out.println(getCurThreadName() + " 让子弹飞一会儿.");
		System.out.println(getCurThreadName() + " 做一点自己的事情.");

		for (int i = 0; i < COMPUTE_TIMES / 2; i++) {
			int j = i * 10000;
		}
		
		System.out.println(getCurThreadName() + " 获取并发任务的执行结果.");
		
		try {
			//5.调用FutureTask对象的get()方法阻塞性地获得并发线程的执行结果。
			//线程阻塞，等待上面所有线程执行完毕后，输出结果。
			System.out.println(thread.getName() + " 线程占用时间： " + futureTask.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println(getCurThreadName() + " 运行结束.");
	}
}
